package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vo.ContentVO;
import com.heima.wemedia.entity.TextAndImage;
import com.heima.wemedia.mapper.ChannelsMapper;
import com.heima.wemedia.mapper.NewsMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.AutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class AutoScanServiceImpl implements AutoScanService {
    @Autowired
    private GreenTextScan greenTextScan;//文本审核
    @Autowired
    private GreenImageScan greenImageScan;//图片审核
    @Autowired
    private FileStorageService fileStorageService;//minio
    @Autowired
    private NewsMapper newsMapper;
    @Autowired
    private IArticleClient articleClient;//远程
    @Autowired
    private WmUserMapper userMapper;
    @Autowired
    private ChannelsMapper channelsMapper;
    @Override
    @Async//让这个方法变成异步方法
    public void autoScan(WmNews wmNews) {
        TextAndImage textAndImage = getTextAndImage(wmNews);
        //文本审核
       boolean result = autoScanText(textAndImage.getText(),wmNews);
       if ( !result){
           return;
       }
        //图片审核
        result = autoScanImage(textAndImage.getUrls(),wmNews);
        if (!result){
            return;
        }
        //发布文章
        ResponseResult resp = saveArticleApp(wmNews);
        if (resp != null && Objects.equals(resp.getCode(),AppHttpCodeEnum.SUCCESS.getCode())){
            //数据保存到数据库,设置状态为9成功处理
            Long articleId = (Long) resp.getData();
            wmNews.setArticleId(articleId);
            updateStatus(wmNews, WmNews.Status.PUBLISHED,"审核成功");
        }else {
            throw  new CustomException(AppHttpCodeEnum.SERVER_ERROR);
        }


    }
    //发布文章
    private ResponseResult saveArticleApp(WmNews wmNews) {
        ArticleDto articleDto = new ArticleDto();
        //写文章拷贝到读文章
        BeanUtils.copyProperties(wmNews,articleDto);

        articleDto.setId(wmNews.getArticleId());
        //解决空指针异常
        //Integer id = WmThreadLocalUtil.getUser().getId();
        Integer id = wmNews.getUserId();

        articleDto.setAuthorId(Long.valueOf(id));
        //作者名字查询一次
        WmUser wmUser = userMapper.selectById(id);
        if (wmUser != null){
            articleDto.setAuthorName(wmUser.getName());
        }
        //查询频道名称
        WmChannel wmChannel = channelsMapper.selectById(wmNews.getChannelId());
        if (wmChannel != null){
            articleDto.setChannelName(wmChannel.getName());
        }
        articleDto.setLayout(wmNews.getType());
        articleDto.setCreatedTime(new Date());


        return articleClient.saveArticle(articleDto);
    }

    //审核图片
    private boolean autoScanImage(List<String> urls, WmNews wmNews) {
        //url集合->图片byte[]
        List<byte[]> bytelist = new ArrayList<>();
        for (String url : urls) {
            byte[] bytes = fileStorageService.downLoadFile(url);
            bytelist.add(bytes);
        }
        try {
            Map map = greenImageScan.imageScan(bytelist);
            if (map != null){
                String suggestion = (String) map.get("suggestion");
                if (Objects.equals(suggestion,"pass")){
                    //成功
                    return true;
                }else if (Objects.equals(suggestion,"review")){
                    updateStatus(wmNews, WmNews.Status.ADMIN_AUTH, "文章图片中可能包违规内容,需要人工审核");
                    //转人工
                    return false;
                }else if (Objects.equals(suggestion,"block")){
                    updateStatus(wmNews, WmNews.Status.FAIL, "文章图片中包含违规内容");
                    //拒绝
                    return false;
                }
            }
        } catch (Exception e) {
            log.error("调用阿里云接口失败",e);
        }
        updateStatus(wmNews, WmNews.Status.ADMIN_AUTH, "文章图片中可能包违规内容,需要人工审核");
        return false;
    }

    //审核文本
    private boolean autoScanText(String text, WmNews wmNews) {
        try {
            Map map = greenTextScan.greeTextScan(text);
            if (map != null){
                String suggestion = (String) map.get("suggestion");
                if (Objects.equals(suggestion,"pass")){
                    //成功
                    return true;
                }else if (Objects.equals(suggestion,"review")){
                    updateStatus(wmNews, WmNews.Status.ADMIN_AUTH, "文章内容可能包含敏感词,需要人工审核");
                    //转人工
                    return false;
                }else if (Objects.equals(suggestion,"block")){
                    updateStatus(wmNews, WmNews.Status.FAIL, "文章内容包含敏感词");
                    //拒绝
                    return false;
                }
            }
        } catch (Exception e) {
            log.error("调用阿里云接口失败",e);
        }
        updateStatus(wmNews, WmNews.Status.ADMIN_AUTH, "文章内容可能包含敏感词,需要人工审核");
        return false;
    }
    //更新状态
    private void updateStatus(WmNews wmNews, WmNews.Status adminAuth, String reason) {
        wmNews.setStatus(adminAuth.getCode());
        wmNews.setReason(reason);
        newsMapper.updateById(wmNews);
    }
    //文本和标题处理
    private TextAndImage getTextAndImage(WmNews wmNews) {
         Set<String> urls = new HashSet<>();
        //处理内容
        StringBuilder builder = new StringBuilder();
        String content = wmNews.getContent();
        List<ContentVO> contentVOS = JSONArray.parseArray(content, ContentVO.class);
        for (ContentVO contentVO : contentVOS) {
            if (Objects.equals(contentVO.getType(),"image")){
                String url = contentVO.getValue();
                urls.add(url);
            }else if (Objects.equals(contentVO.getType(),"text")){
                builder.append(contentVO.getValue());
                builder.append("-");
            }
        }
        //处理标题
        builder.append(wmNews.getTitle());
        builder.append("-");
        //处理封面中的图片
        String images = wmNews.getImages();
        if (StringUtils.isNotBlank(images)){
            String[] split = images.split(",");
            urls.addAll(Arrays.asList(split));
        }
        TextAndImage textAndImage = new TextAndImage();
        textAndImage.setText(builder.toString());
        textAndImage.setUrls(new ArrayList<>(urls));

        return textAndImage;
    }
}
